package com.banciyuan.bcywebview.biz.post.cos;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.post.Listener.OnTextChangeListener;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.daoexample.model.Character;
import de.greenrobot.daoexample.model.PostItem;

/**
 * Created by squall on 2015/12/30.
 */
public class CosInfoActivity extends BaseActivity implements View.OnClickListener {

    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private EditText et_title;
    private EditText et_intro;
    private EditText et_tags;
    private FlowView tag_area;
    private FlowView re_tags_area;
    private TextView tv_add_tag;
    private LinearLayout draw_warn;
    private TextView title_nums;
    private TextView intro_nums;

    private PostItem postItem;
    private PostItem.Optional optional;
    private String history;
    private RequestQueue queue;

    private boolean operation_flag = false;
    private boolean show_tag = true;
    private Set<String> mTagSet = new LinkedHashSet<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post_info_set);
        initArgs();
        initActionbar();
        initUi();
        initAction();
        getTagFromDiskMemory();
        initData();
        getState();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
        Gson gson = new Gson();
        postItem = (PostItem) getIntent().getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        show_tag = getIntent().getBooleanExtra(gotoUtil.INTENT_VALUE_TWO, true);
        history = gson.toJson(postItem.getOptional());
        optional = postItem.getOptional();
    }

    private void getTagFromDiskMemory() {
        Gson gson = new Gson();
        String tagStr = SPHelper.getString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.COSTAG, "[]");
        mTagSet = gson.fromJson(tagStr, new TypeToken<LinkedHashSet<String>>() {
        }.getType());
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.add_more_info));
        mActionbarHelper.setActionCallbacks(new ActionbarHelper.OnActionCallbacks() {
            @Override
            public void onBackClick() {
                finishActivity();
                hideSoftKeyboard();
                finish();
            }

            @Override
            public void onActionClick(int id) {

            }
        });
    }

    @Override
    protected void initUi() {
        et_title = (EditText) findViewById(R.id.et_title);
        et_intro = (EditText) findViewById(R.id.et_intro);
        et_tags = (EditText) findViewById(R.id.et_tags);
        tag_area = (FlowView) findViewById(R.id.tag_area);
        re_tags_area = (FlowView) findViewById(R.id.re_tags_area);
        tv_add_tag = (TextView) findViewById(R.id.tag_group_add);
        draw_warn = (LinearLayout) findViewById(R.id.draw_warn);
        title_nums = (TextView) findViewById(R.id.title_nums);
        intro_nums = (TextView) findViewById(R.id.intro_nums);
        draw_warn.setVisibility(View.GONE);
        et_title.setHint(getString(R.string.cos_title));
        ((View) findViewById(R.id.rl_add_character).getParent()).setVisibility(View.GONE);
        re_tags_area.removeAllViews();
        if (!show_tag) {
            findViewById(R.id.tag_main).setVisibility(View.GONE);
        }
    }


    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + CoserApi.getRecommendtags();
        List<BcyPair> param = new ArrayList<BcyPair>();
        param.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(CosInfoActivity.this).getToken()));
        Map<String, String> map = HttpUtils.getData(param);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, CosInfoActivity.this)) {
                    re_tags_area.setVisibility(View.VISIBLE);
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        Gson gson = new Gson();
                        List<String> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<String>>() {
                        }.getType());
                        mTagSet.addAll(templist);
                        for (final String name : mTagSet) {
                            View tags = View.inflate(CosInfoActivity.this, R.layout.tag_nomargin_blue, null);
                            TextView tv = (TextView) tags.findViewById(R.id.single_tag);
                            tv.setText(name);
                            tags.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    addTag(name);
                                }
                            });
                            re_tags_area.addView(tags);
                        }
                    } catch (JSONException e) {
                        re_tags_area.setVisibility(View.GONE);
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                re_tags_area.setVisibility(View.GONE);
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, CosInfoActivity.this, map);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(stringRequestParam);
    }

    private void getState() {
        if (!TextUtils.isEmpty(optional.getContent())) {
            et_intro.setText(optional.getContent());
        }
        if (!TextUtils.isEmpty(optional.getTitle())) {
            et_title.setText(optional.getTitle());
        }
        if (optional.getTags() != null && !optional.getTags().isEmpty()) {
            tag_area.removeAllViews();
            if (tag_area.getVisibility() == View.GONE) tag_area.setVisibility(View.VISIBLE);
            for (String s : optional.getTags()) {
                addTagView(s);
            }
        }
    }

    @Override
    protected void initAction() {
        tv_add_tag.setOnClickListener(this);
        et_title.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 20) {
                    title_nums.setVisibility(View.VISIBLE);
                    title_nums.setText(s.length() + "/30");
                } else {
                    title_nums.setVisibility(View.GONE);
                }
            }
        });

        et_intro.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 4990) {
                    intro_nums.setVisibility(View.VISIBLE);
                    intro_nums.setText(s.length() + "/5000");
                } else {
                    intro_nums.setVisibility(View.GONE);
                }
            }
        });

        et_tags.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    addTag(et_tags.getText().toString());
                }
                return true;
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tag_group_add:
                addTag(et_tags.getText().toString());
                break;
        }
    }

    private void addTag(String name) {
        if (optional.getTags().size() < 5) {
            if (!operation_flag) {
                operation_flag = true;
                if (!TextUtils.isEmpty(name)) {
                    if (name.equals(postItem.getWork())) {
                        MyToast.show(this, getString(R.string.tag_work_cannot_repeat));
                        operation_flag = false;
                        return;
                    }
                    for (Character role : postItem.getCharacter()) {
                        if (name.equals(role.getCharacter())) {
                            MyToast.show(this, getString(R.string.tag_role_cannot_repeat));
                            operation_flag = false;
                            return;
                        }
                    }
                    if (tag_area.getVisibility() == View.GONE) tag_area.setVisibility(View.VISIBLE);
                    for (int i = 0; i < optional.getTags().size(); i++) {
                        if (optional.getTags().get(i).equals(name)) {
                            MyToast.show(CosInfoActivity.this, getString(R.string.tag_not_equal));
                            operation_flag = false;
                            return;
                        }
                    }
                    addTagView(name);
                    optional.getTags().add(name);
                    et_tags.setText("");
                } else {
                    MyToast.show(CosInfoActivity.this, getString(R.string.tag_not_null));
                }
                operation_flag = false;
            }
        } else {
            MyToast.show(this, getString(R.string.label_five_limit));
        }
    }

    private void addTagView(final String name) {
        final View tag = View.inflate(CosInfoActivity.this, R.layout.tag_blue_cancel, null);
        TextView tv_name = (TextView) tag.findViewById(R.id.single_tag_cancel);
        tv_name.setText(name);
        tag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tag_area.removeView(tag);
                removeTag(name);
                if (tag_area.getChildCount() == 0) {
                    tag_area.setVisibility(View.GONE);
                }
            }
        });
        tag_area.addView(tag);
    }

    private void removeTag(String name) {
        if (!operation_flag) {
            operation_flag = true;
            optional.getTags().remove(name);
            operation_flag = false;
        }
    }

    @Override
    public void onBackPressed() {
        finishActivity();
        super.onBackPressed();
    }

    private void finishActivity() {
        if (et_title.getText() != null) {
            optional.setTitle(et_title.getText().toString());
        }
        if (et_intro.getText() != null) {
            optional.setContent(et_intro.getText().toString());
        }
        postItem.setOptional(optional);
        Intent intent = new Intent();
        if (!TextUtils.isEmpty(et_title.getText())
                || !TextUtils.isEmpty(et_intro.getText())
                || (optional.getTags() != null && !optional.getTags().isEmpty())) {
            intent.putExtra("change", true);
        } else {
            intent.putExtra("change", false);
        }
        intent.putExtra("postitem", postItem);
        setResult(CosPostActivity.GO_SETINFO, intent);
    }

    public void hideSoftKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputManager && inputManager.isActive()) {
            inputManager.hideSoftInputFromWindow(et_title.getApplicationWindowToken(), 0);
        }
    }
}
